//
//  XGL_StoreProductManager.swift
//  XGamesLive
//
//  Created by ios on 2024/5/31.
//

import Foundation
import SwiftyStoreKit
import SwiftyJSON

class XGL_PurchaseManager{
    static let share = XGL_PurchaseManager()
    
    func xgl_transactions()  {
        SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
            for purchase in purchases {
                switch purchase.transaction.transactionState {
                case .purchased:
                    if purchase.needsFinishTransaction {
                        // Deliver content from server,
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                    // Unlock content
                case .restored:
                    if purchase.needsFinishTransaction {
                        // Deliver content from server,
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                case .failed, .purchasing, .deferred:
                    break // do nothing
                @unknown default:
                    break
                }
            }
        }
    }

    func pay(purchaseProductId:String,completeHandle:@escaping (Bool) -> Void) {
        
        if !SwiftyStoreKit.canMakePayments {
            completeHandle(false)
            return
        }
        
        SwiftyStoreKit.purchaseProduct(purchaseProductId, quantity: 1, atomically: false,simulatesAskToBuyInSandbox: false) { purchaseResult in
            switch purchaseResult {
            case .success(let purchase):
                self.handleTransaction(payId: purchaseProductId,transaction: purchase.transaction) { result in
                    completeHandle(result)
                }
                
            case .error(let error):
                switch error.code {
                case .unknown:
                    print("Unknown error. Please contact support")
                    
                case .clientInvalid:
                    print("Not allowed to make the payment")
                    
                case .paymentCancelled:
                    
                    break
                case .paymentInvalid:
                    
                    print("The purchase identifier was invalid")
                case .paymentNotAllowed:
                    print("The device is not allowed to make the payment")
                    
                case .storeProductNotAvailable:
                    print("The product is not available in the current storefront")
                    
                case .cloudServicePermissionDenied:
                    print("Access to cloud service information is not allowed")
                    
                case .cloudServiceNetworkConnectionFailed:
                    print("Could not connect to the network")
                    
                case .cloudServiceRevoked:
                    print("User has revoked permission to use this cloud service")
                    
                default :
                    print("other error")
                }
                
                completeHandle(false)
            }
        }
    }
    

    func handleTransaction(payId: String,transaction:PaymentTransaction,completeHandle:@escaping ((Bool) -> Void)) {
  
        SwiftyStoreKit.fetchReceipt(forceRefresh:false) { result in
            
            switch result {
                
            case .success(let receiptData):
                
                let encryptedReceipt = receiptData.base64EncodedString(options: [])
                
                print("Fetch receipt success:\n\(encryptedReceipt)")

                self.payResultRequest(transactionReceipt: encryptedReceipt) { result in
                    if result {
                        SwiftyStoreKit.finishTransaction(transaction)
                        completeHandle(true)
                    }else{
                        completeHandle(false)
                    }
                }
                break
            case .error(let error):
                print(" --- Fetch receipt failed: \(error)")
                completeHandle(false)
//                if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL, FileManager.default.fileExists(atPath: appStoreReceiptURL.path) {
//                    do {
//                        let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
//                        print(receiptData)
//                        let receiptString = receiptData.base64EncodedString(options: [])
//                    } catch {
//                        print("Couldn't read receipt data with error: " + error.localizedDescription)
//                    }
//                }
                break
            }
            
        }
        
    }
    
    func restorePurchases(_ completeHolder: ((Bool)->Void)? = nil) {
        
        SwiftyStoreKit.restorePurchases(atomically: false) { results in
            let queue = DispatchQueue.init(label: "PurchasesRestoreQueue")
            let group = DispatchGroup()
            
            if results.restoreFailedPurchases.count > 0 {
                print("Restore Failed: \(results.restoreFailedPurchases)")
            }else if results.restoredPurchases.count > 0 {
               
                for purchase in results.restoredPurchases {
//                    handleTransaction(transaction: purchase) { dialog, code in }
                    group.enter()
                    self.handleTransaction(payId: purchase.productId,transaction: purchase.transaction) { result in
                        group.leave()
                    }
                }
                print("Restore Success: \(results.restoredPurchases)")
            }
            else {
                print("Nothing to Restore")
            }
            group.notify(queue: queue) {
                DispatchQueue.main.async(execute: {
                    if completeHolder != nil {
                        completeHolder!(true)
                    }
                })
            }
        }
        
    }
}

extension XGL_PurchaseManager{
    private func payResultRequest(transactionReceipt: String,complete:@escaping (_ result: Bool)->Void) {
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(CustomRequestAPI(requestAPI: .rechargeWithAppleCheck(billNo: transactionReceipt))) { result in
            switch result{
            case .success(let response):
                if let result = NSInteger(response.resultJson) {
                    complete(false)
                    if result == 1 {
                        MXProgressHUD.hudWithText("Order processing failure")
                    }
                }else{
                    complete(true)
                }
                break
            default:
                break
            }
        }
    }
}
